<template>
  <div style="height: 100%">
    <div v-transfer-dom>
      <popup :value="true"
             height="100%"
             :should-rerender-on-show="true"
             :show-mask="false"
             :hide-on-blur="false"
             :popup-style="{'z-index':'999', 'background':'#fff'}">
        <x-header :left-options="{backText: '',preventGoBack:true}"
                  title="附件"
                  @on-click-back="goBack()"></x-header>
        <div class="popup-head-bottom-container">
          <div style="position:relative;top:10%;text-align:center;">
            <icon :name="fileIcon(name)"
                  class="preview-file"></icon>
            <div style="text-align:center;margin:0 2rem 1rem;word-break: break-all;">{{name}}</div>
            <div class="fileSize">{{fileSize | renderFileSize}}</div>
            <!-- <spinner v-if="complete&&fileSize==0" type="spiral" size="30"></spinner>
            <div v-if="complete&&fileSize==0" style="color: rgb(97, 97, 97);font-size:var(--font-size-12);margin-top:1rem;">正在加载</div> -->
            <!-- <div v-if="downloadFlag">
              <x-progress style="margin:1.2rem 4rem 0;" :percent="percent" :show-cancel="false"></x-progress>
              <div style="text-align:center;">{{percent}}%</div>
            </div> -->
            <div style="margin-top:2rem;">
              <svg version="1.1"
                   id="loader-1"
                   xmlns="http://www.w3.org/2000/svg"
                   xmlns:xlink="http://www.w3.org/1999/xlink"
                   x="0px"
                   y="0px"
                   width="50px"
                   height="50px"
                   viewBox="0 0 40 40"
                   enable-background="new 0 0 40 40"
                   xml:space="preserve">
                <path opacity="0.2"
                      fill=""
                      d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946
                  s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634
                  c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"></path>
                <path fill="var(--theme-color-green)"
                      d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0
                  C22.32,8.481,24.301,9.057,26.013,10.047z"
                      transform="rotate(96.7673 20 20)">
                  <animateTransform attributeType="xml"
                                    attributeName="transform"
                                    type="rotate"
                                    from="0 20 20"
                                    to="360 20 20"
                                    dur="0.5s"
                                    repeatCount="indefinite"></animateTransform>
                </path>
              </svg>
              <div style="text-align:center;font-size:var(--font-size-13);color:var(--theme-color-grey)">加载中</div>
            </div>
          </div>
          <div style="position:absolute;bottom:5rem;text-align:center;width:100%;">
            <div v-if="!downloadFlag"
                 style="padding:1rem 8rem;margin-top:3rem;">
              <default-button @click="openHandler()">{{row.fileDownFlag=='1'?'开始下载':'预览'}}</default-button>
            </div>
            <icon v-if="downloadFlag"
                  @click.native="cancel()"
                  name="cancel"
                  style="width:3rem;height:3rem;color:#a9a9a9;"></icon>
          </div>
        </div>
      </popup>
    </div>
  </div>
</template>
<script>
import defaultButton from '@/components/defaultButton'
export default {
  data () {
    return {
      percent: 0,
      name: '',
      fileSize: '0',
      ft: '',
      complete: true,
      downloadFlag: false
    }
  },
  components: {
    defaultButton
  },
  mounted () {
    this.percent = 0
    this.name = this.row.name
    this.fileSize = this.row.fileSize
    // if (this.row.isTask || (this.row.type != undefined && this.row.type != '')) {
    this.download()
    // } else {
    //   this.downloadWithWatermark()
    // }
    // if (this.row.fileDownFlag=='1') {
    //   this.download()
    // } else if (this.row.fileDownFlag=='0') {
    //   this.downloadWithWatermark()
    // }
    // this.download()
  },
  computed: {
    userInfo () {
      return this.$store.state.user
    },
    row () {
      return this.$store.state.downloadFile
    }
  },
  methods: {
    getUrl () {
      // 获取新的url链接 
      let url = this.COMMON_URL + '?type=customerDownloadService&FixJSON=%7B_method:%27streamSupportService.getAttachment%27,%27_param%27:%7B%27attachmentId%27:%27' + this.row.fileId + '%27%7D%7D'
      url = url.replace(/Action.cmd/, 'StreamSupportAction.cmd')
      if (this.row.type != undefined && this.row.type != '') {
        url = this.row.server
      }
      console.log(url)
      return url
    },
    download () {
      this.downloadFlag = true
      // if (!this.downloadFlag) {
      //   return
      // }
      // this.downloadFlag = false
      const _this = this
      // let url = _this.$store.state.downloadFile.url
      let url = this.getUrl()
      console.log(url)
      let name = _this.$store.state.downloadFile.name
      url = url.replace(/\/\\/, '/').replace(/\\/g, '/')
      let fileUrl = cordova.file.cacheDirectory + name
      let fileTransfer = new FileTransfer()
      _this.ft = fileTransfer
      fileTransfer.onprogress = (progressEvent) => {
        console.log('loaded=' + progressEvent.loaded)
        console.log(_this.row.fileSize)
        if (progressEvent) {
          console.log('watching')
          if (_this.row.fileSize != progressEvent.total) {
            _this.percent = Math.round(progressEvent.loaded * 100 / _this.row.fileSize)
          }
        }
      }
      fileTransfer.download(
        url, fileUrl, (entry) => {
          entry.file(data => {
            // console.log(data)
            if (_this.complete) {
              _this.complete = false
              _this.percent = 100
              cordova.plugins.fileOpener2.open(entry.toURL(), data.type, {
                error: function (e) {
                  console.log(JSON.stringify(e))
                },
                success: function () {
                  console.log('open successfully')
                  _this.complete = false
                  _this.percent = 100
                  _this.$router.go(-1) // 下载完成后不返回
                  _this.$store.commit("DOWNLOAD_FILE", {})
                }
              })
            }
            // showOpenWithDialog使用手机上安装的程序打开下载的文件
          })
          console.log("download complete: " + entry.toURL())
          setTimeout(() => {
            // _this.percent = 100
            // _this.complete = false
            // this.$store.commit("DOWNLOAD_FILE", {})
            // _this.$router.go(-1)
          }, 100)
        },
        (error) => {
          this.percent = 0
          // this.$vux.toast.text("download error code" + error.code)
          // this.$router.go(-1)
          console.log("download error source " + error.source)
          console.log("download error target " + error.target)
          console.log("download error code" + error.code)
        },
        false, {}
      )
    },
    downloadWithWatermark () {
      this.downloadFlag = true
      const _this = this
      const userName = ''
      let queryUserName = encodeURI(this.userInfo.userName)
      queryUserName = queryUserName.replace(/\%/g, '_')
      // let url = this.getReqUrl(this.MOAAPI_URL + '/file/pdf', 'type=integratedsubsys&fileId='+ this.row.fileId  + '&fileType=' +encodeURIComponent(this.row.name) + '&userRealName=' +encodeURIComponent(this.userInfo.userName) + '&userName=' + this.userInfo.loginId)
      let url = this.COMMON_URL + '/file/pdf' + '?type=integratedsubsys&fileId=' + this.row.fileId + '&fileType=' + (this.row.name + '').substring((this.row.name + '').lastIndexOf(".")).toLowerCase() + '&userRealName=' + queryUserName + '&userName=' + this.userInfo.loginId
      url = url.replace(/Action.cmd/, 'StreamSupportAction.cmd')
      let name = _this.$store.state.downloadFile.name
      name = this.changeFileName(name)
      url = url.replace(/\/\\/, '/').replace(/\\/g, '/')
      let fileUrl = cordova.file.cacheDirectory + name
      let fileTransfer = new FileTransfer()
      _this.ft = fileTransfer
      fileTransfer.onprogress = (progressEvent) => {
        console.log('loaded=' + progressEvent.loade)
        console.log(_this.row.fileSize)
        if (progressEvent) {
          console.log('watching')
          if (_this.row.fileSize != progressEvent.total) {
            _this.percent = Math.round(progressEvent.loaded * 100 / _this.fileSize)
          }
        }
      }
      fileTransfer.download(
        url, fileUrl, (entry) => {
          entry.file(data => {
            // console.log(data)
            if (_this.complete) {
              _this.complete = false
              _this.percent = 100
              cordova.plugins.fileOpener2.open(entry.toURL(), data.type, {
                error: function (e) {
                  console.log(JSON.stringify(e))
                },
                success: function () {
                  console.log('open successfully')
                  _this.complete = false
                  _this.percent = 100
                  _this.$router.go(-1) // 下载完成后返回
                  _this.$store.commit("DOWNLOAD_FILE", {})
                }
              })
            }
            // showOpenWithDialog使用手机上安装的程序打开下载的文件
          })
          console.log("download complete: " + entry.toURL())
          setTimeout(() => {
            // _this.percent = 100
            // _this.complete = false
            // this.$store.commit("DOWNLOAD_FILE", {})
            // _this.$router.go(-1)
          }, 100)
        },
        (error) => {
          this.percent = 0
          // this.$vux.toast.text("download error code" + error.code)
          // this.$router.go(-1)
          console.log(error)
          console.log("download error source " + error.source)
          console.log("download error target " + error.target)
          console.log("download error code" + error.code)
        },
        false, {}
      )
    },
    openHandler () {
      // let a = 'http://webcms.ecidi.com/integratedsubsys/servlet/StreamSupportAction.cmd?type=customerDownloadService&FixJSON=%7B_method:%27streamSupportService.getAttachment%27,%27_param%27:%7B%27attachmentId%27:%2752c2243e6ae9d8e2fb0ecf68546e477d%27%7D%7D'
      let url = this.row.belongSubSys + '?type=customerDownloadService&FixJSON=%7B_method:%27streamSupportService.getAttachment%27,%27_param%27:%7B%27attachmentId%27:%27' + this.row.fileId + '%27%7D%7D'
      // url = url.replace(/Action.cmd?/, 'StreamSupportAction.cmd?')
      // this.downloadFlag = true
      url = this.getReqUrl('http://10.215.2.172:8987/' + 'moaapi/file/pdf') + '&url=' + this.row.belongSubSys + '?type=customerDownloadService' + '&FixJSON=' + ('%7B_method:%27streamSupportService.getAttachment%27,%27_param%27:%7B%27attachmentId%27:%27' + this.row.fileId + '%27%7D%7D') + '&fileName=' + encodeURI(this.row.name) + '&userRealName=' + encodeURI(this.userInfo.userName) + '&userName=' + this.userInfo.loginId
      // url = this.getReqUrl(this.MOAAPI_URL + '/file/pdf', 'url='+ encodeURIComponent(this.row.belongSubSys) + '&type=customerDownloadService' + '&fixJson=' + encodeURIComponent('%7B_method:%27streamSupportService.getAttachment%27,%27_param%27:%7B%27attachmentId%27:%27'+ this.row.fileId +'%27%7D%7D') + '&fileName=' +encodeURIComponent(this.row.name) + '&userRealName=' +encodeURIComponent(this.userInfo.userName) + '&userName=' + this.userInfo.loginId)
      url = this.getReqUrl('http://10.215.2.172:8987/' + 'moaapi/file/pdf', 'type=integratedsubsys&fileId=' + this.row.fileId + '&fileType=' + (this.row.name + '').substring((this.row.name + '').lastIndexOf(".")).toLowerCase() + '&userRealName=' + encodeURIComponent(this.userInfo.userName) + '&userName=' + this.userInfo.loginId)
      url = url.replace(/Action.cmd/, 'StreamSupportAction.cmd')
      url = url.replace(/\/\\/, '/').replace(/\\/g, '/')
      this.$http({
        method: 'get',
        url: url
      }).then(res => {
        console.log(res)
      })
      // if (this.row.fileDownFlag == '0') {
      //   this.downloadFlag = true
      //   this.download()
      // } else if (this.row.fileDownFlag == '1') {

      // }
    },
    cancel () {
      this.ft.abort()
      this.$router.go(-1)
    },
    goBack () { // 左上角返回事件
      this.ft.abort()
      this.$router.go(-1)
    },
    changeFileName (name) {
      const type = (name + '').substring((name + '').lastIndexOf(".")).toLowerCase()
      const fileName = (name + '').substring(0, (name + '').lastIndexOf("."))
      switch (type) {
        case '.docx':
        case '.doc':
        case '.xlsx':
        case '.xls':
        case '.ppt':
        case '.pptx':
          return fileName + '.pdf'
        default:
          return name
      }
    },
    fileIcon (name) {
      const data = name + ''
      switch (data.substring(data.lastIndexOf(".")).toLowerCase()) {
        case '.dir':
          return 'doc_folder'
        case '.docx':
          return 'doc_word'
        case '.doc':
          return 'doc_word'
        case '.pdf':
          return 'doc_pdf'
        case '.xlsx':
          return 'doc_excel'
        case '.rar':
          return 'doc_zip'
        case '.zip':
          return 'doc_zip'
        case '.ppt':
          return 'doc_ppt'
        case '.pptx':
          return 'doc_ppt'
        case '.txt':
          return 'doc_txt'
        case '.html':
          return 'doc_html'
        case '.exe':
          return 'doc_exe'
        case '.jpg':
        case '.png':
        case '.jpeg':
        case '.gif':
        case '.bmp':
          return 'doc_img'
        case '.amr':
        case '.wav':
          return 'doc_music'
        case '.mp4':
        case '.mov':
          return 'doc_video'
        default:
          return 'doc_blank'
      }
    }
  }
}

</script>
<style lang="less" scoped>
.fileSize {
  text-align: center;
  font-size: 0.6rem;
  color: #a9a9a9;
}
.preview-file {
  padding: 2rem 0 1rem;
  width: 20%;
  height: auto;
}
</style>
